package at.jku.se.pr.quickshopperserver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.*;

/**
 * Servlet implementation class
 */
@WebServlet("/QuickShopperServer")
public class QuickShopperServer extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
	
	/**
	 * object to perform output actions
	 */
	private PrintWriter out;
	
	/**
	 * database connection object
	 */
	private DBConnection dbConn;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public QuickShopperServer() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	String resultString = convertStreamToString(request.getInputStream());
    	System.out.println("row data from client: " + resultString);
    	
    	out = response.getWriter();
    	dbConn = new DBConnection();
    	JSONObject jsonObj;
    	String responseString = "";
    	
    	char c = resultString.charAt(0);
    	char c2 = resultString.charAt(3);
    	char c3 = resultString.charAt(3);
    	if (c == '{' && c2 == 'u') {
    		// es kommt eine Kundennr. vom Client und es soll geprueft werden, ob Kunde schon vorhanden
    		
    		try {
    			jsonObj = new JSONObject(resultString);
    			
    			dbConn.connect(false);
    			
    			responseString = dbConn.checkCustomerExists(jsonObj);
    		} catch (SQLException e) {
    			System.out.println(e.getErrorCode() + ": " + e.getMessage());
    		} catch(ClassNotFoundException e) {
    			System.out.println(e.getMessage());
    		} catch (JSONException e) {
    			System.out.println(e.getMessage());
			}
    	} else if (c == '{' && c3 == 'a') {
    		// abfrage fuer kassa-barcode
    		
    		try {
    			jsonObj = new JSONObject(resultString);
    			
    			dbConn.connect(false);
    			
    			responseString = dbConn.getDataForCashdesk(jsonObj);
    		} catch (SQLException e) {
    			System.out.println(e.getErrorCode() + ": " + e.getMessage());
    		} catch(ClassNotFoundException e) {
    			System.out.println(e.getMessage());
    		} catch (JSONException e) {
    			System.out.println(e.getMessage());
			}
    	} else if (c == '{') {
    		// eanNr wird abgefragt, dh bezeichnung+einzelpreis aus DB auslesen und an Client schicken
    		
    		try {
    			jsonObj = new JSONObject(resultString);
    			
    			dbConn.connect(false);
    			
    			responseString = dbConn.getDataForEanNr(jsonObj);
    		} catch (SQLException e) {
    			System.out.println(e.getErrorCode() + ": " + e.getMessage());
    		} catch(ClassNotFoundException e) {
    			System.out.println(e.getMessage());
    		} catch (JSONException e) {
    			System.out.println(e.getMessage());
			}
    	}  else if (c == '[') {
    		// es will jemand bezahlen
    		
    		try {
    			JSONArray jsonArray = new JSONArray(resultString);
    			
    			dbConn.connect(true);
    			
    			responseString = dbConn.saveShoppinglist(jsonArray);
    			
    			dbConn.commit();
    		} catch (SQLException e) {
    			System.out.println(e.getErrorCode() + ": " + e.getMessage());
    		} catch(ClassNotFoundException e) {
    			System.out.println(e.getMessage());
    		} catch (JSONException e) {
    			System.out.println(e.getMessage());
			}
    	}
    	
    	System.out.println();
    	out.print(responseString);
		out.flush();
		out.close();
	}
	
	/**
	 * Converts the InputStream of the HTTP-Request to a string
	 * @param is
	 * @return String of is
	 */
	private String convertStreamToString(InputStream is) {
	    String line = "";
	    StringBuilder total = new StringBuilder();
	    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
	    try {
	        while ((line = rd.readLine()) != null) {
	            total.append(line);
	        }
	    } catch (Exception e) {
	    	System.out.println(e.getMessage());
	    }
	    return total.toString();
	}

}
